<template>
	<view>
		<view style="text-align: center; padding: 12px; border-bottom: solid 1px #a1a3a6">确认订单{{ orderType ? " - " + orderType : "" }}</view>
		<view style="margin-top: 10px" v-if="activityItem?.b?.totalCount > 0">
			<u-cell-group>
				<u-cell icon="map" title="请添加收货地址" :isLink="true"></u-cell>
			</u-cell-group>
		</view>
		<view style="padding: 10px; margin-top: 10px">
			<view style="display: flex">
				<image class="slot-image" :src="activityItem.giPrph ? getActivityItemImage(activityItem?.giPrph) : tempImageUrl" mode="widthFix" style="width: 100px; height: 100px"></image>
				<view style="margin-left: 10px">
					<view>{{ activityItem?.giName }}</view>
					<view style="font-size: 14px; color: #a1a3a6; margin-top: 3px">{{ activityItem?.giName }}</view>
					<view style="margin-top: 3px">
						<uni-tag :circle="true" :text="activityItem?.giGrpe + '人团'" type="error" />
					</view>
					<view style="margin-top: 12px">
						<text style="color: red" v-if="orderType === '单独购买'">￥{{ numberFormat(activityItem?.giSppr, 2) }}</text>
						<text style="color: red" v-else>￥{{ numberFormat(activityItem?.giGppr, 2) }}</text>
						<text style="margin-left: 5px; font-size: 12px; text-decoration: line-through">￥{{ numberFormat(activityItem?.giInpr, 2) }}</text>
					</view>
				</view>
			</view>
		</view>
		<view style="margin-top: 5px" v-if="appointment?.gaStat === false">
			<u-cell-group>
				<u-cell icon="bookmark-fill" title="优惠" :value="numberFormat(appointment?.gaDisc, 2)" :isLink="true" :clickable="false"> </u-cell>
			</u-cell-group>
		</view>

		<view style="margin-top: 5px" v-else>
			<u-cell-group>
				<u-cell icon="bookmark-fill" title="优惠" value="活动期间暂无优惠" :isLink="true" :clickable="false"> </u-cell>
			</u-cell-group>
		</view>
		<view style="padding: 10px 0 0 10px; width: 350px;">
			<uni-forms ref="custform" :modelValue="globalUserInfo" label-width="100px" label-align="center">
				<uni-forms-item label="下单人姓名" name="ciName" :rules="[{ required: true, errorMessage: '姓名项必填' }]">
					<uni-easyinput type="text" v-model="globalUserInfo.ciName" placeholder="请输入真实姓名" />
				</uni-forms-item>
			</uni-forms>
		</view>
		<view style="margin-top: 5px">
			<button type="warn" @click="submit('custform')">立即支付</button>
		</view>
	</view>
</template>

<script>
import { mapGetters } from "vuex";
import moment from "moment";
import { createActivityItemsOrder, updateCustomerCiNameByCiUuid } from "../../utils/api.js";

export default {
	props: {
		activityItem: {
			type: Object,
			default() {
				return {};
			},
		},
		appointment: {
			type: Object,
			default() {
				return {};
			},
		},
		orderType: {
			type: String,
			default: "",
		},
		ggUuid: {
			type: String,
			default: "",
		},
		callback: {
			type: Function,
			default: () => {},
		},
		closePopup: {
			type: Function,
			default: () => {},
		},
	},

	data() {
		return {
			tempImageUrl: "http://jdc.jd.com/img/100x100/",
		};
	},

	computed: {
		...mapGetters({
			organizationGateway: "globalInfo/organizationGateway",
			defaultImageBase64: "globalInfo/defaultImageBase64",
			activity: "activityInfo/activity",
			globalUserInfo: "personInfo/userInfo",
		}),
	},

	methods: {
		submit(ref) {
			let userInfo = uni.getStorageSync("userInfo"); // 用户信息
			this.$refs[ref]
				.validate()
				.then((res) => {
					console.log("success", res);
					if (res.ciName !== userInfo.ciName) {
						updateCustomerCiNameByCiUuid({ ciUuid: userInfo.ciUuid, ciName: res.ciName });
						userInfo.ciName = res.ciName;
						this.$store.dispatch("personInfo/save", {
							userInfo: userInfo,
						});
					}
					this.hanldSubmitOrder();
				})
				.catch((err) => {
					console.log("err", err);
				});
		},

		async hanldSubmitOrder() {
			let _this = this;
			let userInfo = uni.getStorageSync("userInfo"); // 用户信息
			let shareId = uni.getStorageSync("shareId") || ""; // 分享人ID
			let staffId = uni.getStorageSync("staffId") || ""; // 员工ID

			if (!userInfo) {
				uni.showToast({ title: "没有您的用户信息", icon: "error", duration: 2000 });
				_this.closePopup();
			}
			if (!userInfo.phone) {
				uni.showToast({ title: "请授权后操作", icon: "error", duration: 2000 });
				_this.closePopup();
			}
			if (!userInfo.ciUuid) {
				uni.showToast({ title: "请登录后操作", icon: "error", duration: 2000 });
				_this.closePopup();
			}
			let nowTime = new Date().getUTCTime();
			const order = {
				// soUuid 订单uuid，服务端生成
				soNumb: moment(nowTime).format("YYYYMMDD") + nowTime, //订单编号
				soType: _this.orderType, // 订单类型
				soItem: _this.activityItem.giUuid, //项目UUID
				soDisc: _this.appointment?.gaStat === false ? Number(_this.appointment?.gaDisc) : 0, //优惠金额
				soCrti: nowTime, //创建时间
				soCuid: userInfo?.ciUuid, //客户UUID
				soNewc: userInfo?.isNew, //客户是否新客
				soCuph: userInfo?.phone,
				soScid: shareId || null, //分享客户UUID
				// soScne  分享客户是否新客
				soStid: staffId || null, //员工UUID
				// soGrid   拼团UUID
				soBook: _this.appointment?.gaStat === false ? true : false, //是否预定
				soStat: "待支付",
				soFrid: _this.activityItem.gpUuid,
				soItin: _this.activityItem,
				scMark: _this.appointment?.gaStat === false ? "活动预定优惠" : "",
				scMone: _this.appointment?.gaStat === false ? Number(_this.appointment?.gaDisc) : 0,
				ggUuid: _this.ggUuid,
			};
			if (_this.orderType === "单独购买") {
				order.soPric = _this.appointment?.gaStat === false ? Number((Number(_this.activityItem.giSppr) - Number(_this.appointment?.gaDisc || 0)).toFixed(2)) : Number(_this.activityItem.giSppr); //成交金额
				order.soGrou = false;
			}
			if (_this.orderType === "新团订单") {
				order.soPric = _this.appointment?.gaStat === false ? Number((Number(_this.activityItem.giGppr) - Number(_this.appointment?.gaDisc || 0)).toFixed(2)) : Number(_this.activityItem.giGppr); //成交金额
				order.soGrou = true;
			}
			if (_this.orderType === "拼团订单") {
				order.soPric = _this.appointment?.gaStat === false ? Number((Number(_this.activityItem.giGppr) - Number(_this.appointment?.gaDisc || 0)).toFixed(2)) : Number(_this.activityItem.giGppr); //成交金额
				order.soGrou = true;
			}
			if (_this.orderType === "参团拼单") {
				order.soPric = _this.appointment?.gaStat === false ? Number((Number(_this.activityItem.giGppr) - Number(_this.appointment?.gaDisc || 0)).toFixed(2)) : Number(_this.activityItem.giGppr); //成交金额
				order.soGrou = true;
			}

			const orderConsumer = {
				// soUuid   后端产生
				puUuid: userInfo.ciUuid, //客户UUID
				puName: userInfo.ciName || null, //客户姓名,
				puAvat: userInfo.avatarUrl,
				puWcna: userInfo.nickName,
				// puPast  客户付款状态
				// puPaid: 付款人UUID
				// puPana  付款人姓名
				// puPati  付款时间
				puType: "个人",
				puPayt: "微信",
				ciPhon: userInfo.phone,
			};

			if (_this.activityItem?.commodities?.totalCount > 0) {
				if (!_this.address) {
					uni.showToast({ title: "没有收货地址信息", icon: "error", duration: 2000 });
					return;
				} else {
					let regionValue = _this.address?.regionValue.split(" ");
					orderConsumer.puRena = _this.address.regionName;
					orderConsumer.puAdpr = regionValue[0];
					orderConsumer.puAdci = regionValue[1];
					orderConsumer.puAdco = regionValue[2];
					orderConsumer.puPhon = _this.address.regionPhone;
					orderConsumer.puAdde = _this.address.regionDetail;
				}
			}
			let ordRes = await createActivityItemsOrder({ order, orderConsumer, openid: userInfo.openId });
			if (ordRes?.soUuid) {
				uni.requestPayment({
					timeStamp: ordRes.timeStamp,
					nonceStr: ordRes.nonceStr,
					package: ordRes.package,
					signType: ordRes.signType,
					paySign: ordRes.paySign,
					success: function (res) {
						if (order.ggUuid) {
							_this.callback({ soUuid: ordRes.soUuid, ggUuid: order.ggUuid, soType: order.soType });
						} else {
							_this.callback({ soUuid: ordRes.soUuid, soType: order.soType });
						}
					},
					fail: function (res) {
						uni.showToast({ title: "用户取消支付", icon: "error", duration: 2000 });
						_this.closePopup();
						return;
					},
				});
			}
		},

		getActivityItemImage(giPrph) {
			let path = "";
			if (typeof giPrph === "string") path = giPrph;
			else if (Array.isArray(giPrph) && giPrph.length > 1) {
				if (typeof giPrph[0] === "string") path = giPrph[0];
				else {
					if (new Date().getUTCTime() >= this.activity.gpStti) {
						const item = giPrph.find((item) => item.display === "3");
						path = item.path || "";
					} else {
						const item = giPrph.find((item) => item.display === "2");
						path = item.path || "";
					}
				}
			} else if (Array.isArray(giPrph) && giPrph.length === 1) {
				if (typeof giPrph[0] === "string") {
					path = giPrph[0];
				} else path = giPrph[0].path || "";
			}
			return path ? this.organizationGateway + "/file/download?filepath=" + path : this.defaultImageBase64;
		},
	},
};
</script>

<style></style>
